"""conf"""

import threading
from os.path import abspath, dirname, join, exists
from os import makedirs
import datetime
from dataclasses import dataclass


from lib.network import get_ip_address
from lib.logger import logger


lock = threading.Lock()


@dataclass
class NoteLevel:
    """note level"""

    ERROR = "error"
    WARN = "warn"
    INFO = "info"


class NoteTaker:
    """note taker"""

    def __init__(self, file_path):
        self.file_path = file_path

        folder_path = dirname(self.file_path)
        if folder_path and not exists(folder_path):
            makedirs(folder_path)

        if not exists(self.file_path):
            open(self.file_path, "w", encoding=GlobalShare.ENCODING_UTF8).close()

    def write_note(self, level, data):
        """write note"""

        lock.acquire()
        try:
            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            log_content = f"[{current_time}][{level}] {data}\n"
            with open(self.file_path, "a", encoding=GlobalShare.ENCODING_UTF8) as file:
                file.write(log_content)
            if level == NoteLevel.ERROR:
                logger.error(log_content)
            elif level == NoteLevel.WARN:
                logger.warning(log_content)
            elif level == NoteLevel.INFO:
                logger.info(log_content)
            else:
                logger.debug(log_content)
        finally:
            lock.release()

    def error(self, data):
        """write error note"""

        self.write_note(level=NoteLevel.ERROR, data=data)

    def warn(self, data):
        """write warn note"""

        self.write_note(level=NoteLevel.WARN, data=data)

    def info(self, data):
        """write info note"""

        self.write_note(level=NoteLevel.INFO, data=data)


@dataclass
class GlobalShare:
    """全局共享数据类"""

    ENCODING_UTF8 = "utf-8"
    AGENT_IP = get_ip_address()
    AGENT_PORT = 8001
    ROOT_DIR = abspath(dirname(dirname(__file__)))
    WORKSPACE_DIR = join(ROOT_DIR, "workspace")
    LOGS_DIR = join(ROOT_DIR, "logs")
    NOTES_LOG_PATH = join(LOGS_DIR, "notes.log")
    ERROR_NOTES_LOG_PATH = join(LOGS_DIR, "error_notes.log")
    CACHE_DIR = join(ROOT_DIR, "cache")
    SUCC_CODE = 0
    SUCC_RESP = {"code": SUCC_CODE, "msg": "succ"}
    GIT_USER = "git_peqa"
    GIT_PWD = "Altruism1234"
    REPOS = {
        "pressure": f"https://{GIT_USER}:{GIT_PWD}@jidudev.com/test_cases/pressure.git"
    }


note_taker = NoteTaker(file_path=GlobalShare.NOTES_LOG_PATH)
error_note_taker = NoteTaker(file_path=GlobalShare.ERROR_NOTES_LOG_PATH)
